package com.hz.ruoyimqttconsume.handler;

import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.system.api.EquipmentService;
import com.ruoyi.system.api.domain.AgrAlertLinkResultVo;
import com.ruoyi.system.api.domain.AgrAlertRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * 死信队列消费者
 */
@Service
@Slf4j
public class DLXConsumerService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private EquipmentService equipmentService;

    @RabbitListener(queues = "dlx.queue")
    public void handleDLXMessage(Map<String, Object> message, Channel channel, Message amqpMessage) throws IOException {
       // String code = (String) message.get("code");
        String alertInfo = (String) message.get("alertInfo");
        String exeTime = (String) message.get("exeTime");
        AgrAlertLinkResultVo agrAlertLinkResultVo = (AgrAlertLinkResultVo) message.get("agrAlertLinkResultVo");
        log.warn("收到死信队列消息: {}", message);

        try {
            // 插入记录表
            AgrAlertRecordVo agrAlertRecordVo = new AgrAlertRecordVo();
            agrAlertRecordVo.setSourceId(agrAlertLinkResultVo.getSourceId());
            agrAlertRecordVo.setTargetId(agrAlertLinkResultVo.getTargetId());
            agrAlertRecordVo.setFieldId(agrAlertLinkResultVo.getFieldId());
            agrAlertRecordVo.setAlertTime(exeTime);
            agrAlertRecordVo.setPlotsId(agrAlertLinkResultVo.getPlotsId());
            agrAlertRecordVo.setExeTime(agrAlertLinkResultVo.getExeTime());
            agrAlertRecordVo.setExceptionId((long) agrAlertLinkResultVo.getExeCondition());
            agrAlertRecordVo.setAlertType("短信");
            agrAlertRecordVo.setAlertInfo(alertInfo);
            log.info("插入记录表: {}", agrAlertRecordVo);
            equipmentService.add(agrAlertRecordVo);
            // 记录预警信息逻辑
            log.info("记录预警信息: {}", agrAlertRecordVo);

            // 手动确认消息
            channel.basicAck(amqpMessage.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("处理死信(延时)消息失败: {}", message, e);
            // 拒绝消息并丢弃
            channel.basicNack(amqpMessage.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}